package com.association.main.controller;


import com.association.main.common.R;

import com.association.main.domain.*;
import com.association.main.dto.VoteDto;
import com.association.main.service.*;
import com.association.main.utils.JwtUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import lombok.extern.slf4j.Slf4j;
import org.apache.tomcat.jni.Local;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;
@Slf4j
@RestController
@RequestMapping("/vote")
public class VoteController {
    @Autowired
    private VoteService voteService;

    @Autowired
    private VoteOptionService voteOptionService;

    @Autowired
    private UsersService usersService;

    @Autowired
    private ClubsService clubsService;

    @Autowired
    private VoteRecordService voteRecordService;

    @Autowired
    private MembersService membersService;
    @GetMapping
    public R<Page> voteList(int page, int pageSize, Integer clubId){
        Page pageInfo=new Page(page,pageSize);
        LambdaQueryWrapper<Vote> voteServiceLambdaQueryWrapper=new LambdaQueryWrapper<>();
        voteServiceLambdaQueryWrapper.orderByDesc(Vote::getStartTime);
        voteServiceLambdaQueryWrapper.eq(clubId!=null,Vote::getClubId,clubId);
        voteService.page(pageInfo,voteServiceLambdaQueryWrapper);
        List<Vote> list = voteService.list(voteServiceLambdaQueryWrapper);
        List<VoteDto> voteDtos=list.stream().map((item)->{
            VoteDto voteDto=new VoteDto();
            BeanUtils.copyProperties(item,voteDto);
            Users users = usersService.getById(item.getUserId());
            Clubs clubs = clubsService.getById(item.getClubId());
            voteDto.setClubs(clubs);
            voteDto.setUsers(users);
            return voteDto;
        }).collect(Collectors.toList());
        pageInfo.setRecords(voteDtos);
        return R.success(pageInfo);
    }


    @PostMapping
    @Transactional
    public R<String> addVote(@RequestBody Map data, HttpServletRequest request){
        String token = request.getHeader("token");
        Integer userId = JwtUtil.getUserId(token);
        DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd'T'HH:mm:ss'.000Z'");
        Vote vote = new Vote();
        vote.setId((Integer) data.get("id"));
        vote.setClubId((Integer) data.get("clubId"));
        vote.setStartTime(LocalDateTime.parse((String)data.get("startTime"),formatter));
        vote.setEndTime(LocalDateTime.parse((String)data.get("endTime"),formatter) );
        vote.setTitle((String) data.get("title"));
        vote.setDescription((String) data.get("description"));
        vote.setUserId(userId);
        voteService.save(vote);
        List<Map> option=(List<Map>) data.get("option");
        List<VoteOption> voteOptions=new ArrayList<>();
        for(int i=0;i<option.size();i++){
            VoteOption voteOption = new VoteOption();
            voteOption.setName((String)option.get(i).get("name"));
            voteOption.setVoteId(vote.getId());
            voteOptions.add(voteOption);
        }
        voteOptionService.saveBatch(voteOptions);
        return R.success("添加成功了");
    }


    @DeleteMapping
    public R<String> delete(@RequestBody Vote vote){
        voteService.removeById(vote.getId());
        return R.success(20000,"删除成功");
    }



    @GetMapping("/record")
    public R<List<Map<String,Integer>>> voteRecord(int id){
        //首先接收的是投票的ID
        LambdaQueryWrapper<VoteOption> voteOptionLambdaQueryWrapper=new LambdaQueryWrapper<>();
        voteOptionLambdaQueryWrapper.eq(VoteOption::getVoteId,id);
        List<VoteOption> voteOptions = voteOptionService.list(voteOptionLambdaQueryWrapper);
        List<Map<String,Integer>> record=new ArrayList<>();
        for(int i=0;i<voteOptions.size();i++){
            Integer voteOptionId = voteOptions.get(i).getId();
            String voteOptionName = voteOptions.get(i).getName();
            LambdaQueryWrapper<VoteRecord> voteRecordLambdaQueryWrapper=new LambdaQueryWrapper<>();
            voteRecordLambdaQueryWrapper.eq(VoteRecord::getVoteOptionId,voteOptionId);
            int count = voteRecordService.count(voteRecordLambdaQueryWrapper);
            Map recodeMap=new HashMap();
            recodeMap.put("id",voteOptionId);
            recodeMap.put("name",voteOptionName);
            recodeMap.put("count",count);
            record.add(i,recodeMap);
        }
        //根据投票的ID遍历选项
        //根据选项的ID来统计投票个数
        return R.success(record);
    }


    @GetMapping("/recordAdd")
    public R<List<Map>> voteRecordAdd(Integer id){
        //接受的是option的ID,获取选项名称
        VoteOption voteOption = voteOptionService.getById(id);
        String name = voteOption.getName();
        Integer optionId = voteOption.getId();
        //name->也就是选项名称
        LambdaQueryWrapper<VoteRecord> voteRecordLambdaQueryWrapper=new LambdaQueryWrapper<>();
        voteRecordLambdaQueryWrapper.eq(VoteRecord::getVoteOptionId,optionId);
        List<VoteRecord> voteRecords = voteRecordService.list(voteRecordLambdaQueryWrapper);

        List<Map> mapList=new ArrayList<>();
        for(int i=0;i<voteRecords.size();i++){
            Map map= new HashMap();
            Integer memberId = voteRecords.get(i).getMemberId();
            Members members = membersService.getById(memberId);
            map.put("name",members.getName()+"["+ members
                    .getUsername()+"]");
            map.put("optionName",name);
            mapList.add(i,map);
        }


        return R.success(mapList);
    }







}
